package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CustInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.AssemblyAttrDtoUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.AreaNameCache;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.IPersonAttrDealService;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CustInfoModuleHandler extends AbstractModuleHandler {


    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private IPersonAttrDealService personAttrDealService;

    @Autowired
    IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    //新装模板对应的客户信息组件处理
    @Override
    public List<ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {


        //只查showType为D的
        List<InstAttrDTO> attrConfigs = queryScenePersonService.listCustInfoAttrs(context.getAcceptRequest().getSceneInstId())
            .getResultObject().stream().filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType())).collect(Collectors.toList());

        List<CommonAttrVO> commonAttrList =  AssemblyAttrDtoUtils.assemblyVO(attrConfigs);
        commonAttrList.forEach(attr -> {
            attr.setDefaultValue(attr.getValueDesc());
        });
        //客户信息需要初始化
        personAttrDealService.initAttrList(commonAttrList);
        // 过户质检/重提环节重新组装老客户的客户信息
        String sceneInstId = context.getSceneVo().getSceneInstId();
        String serviceOfferId = context.getAcceptRequest().getServiceOfferId();
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        if (KiteStringUtils.equalsAny(taskCode, "OrderResubmit", "OrderSignedCheckSHZWY", "OrderResubmitZWY")
            && KiteStringUtils.equals(ServiceOfferConsts.SERVICE_OFFER_TRANSFER, serviceOfferId)) {
            String orderId = this.querySceneInstService
                .getExtParameterValue(context.getSceneVo().getSceneInstId(), "outOrderId");
            Map<String, Object> orderInfo = orderService.getOrderDetail(orderId);
            KitePosDTO kitePosDTO = JSONObject
                .toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
            List<KitePosAttrDTO> attrs = kitePosDTO.getCustomer().getAttrs();
            String oldCustId = "";
            String oldGroupId = "";
            String oldProvinceCode = "";
            String oldEparchyCode = "";
            String oldRegionId = "";
            String oldLocationValue = "";
            String oldLocationValueDesc = "";
            String groupOldCustName = "";

            if (KiteListUtils.isNotEmpty(attrs)) {
                List<String> regionCodes = new ArrayList<>();
                for (KitePosAttrDTO attr : attrs) {
                    if (KiteStringUtils.equals("oldCustId", attr.getCode())) {
                        oldCustId = attr.getValue();
                        operateSceneInstService.putExtParameter(sceneInstId, "oldCustId", oldCustId);
                    }
                    if (KiteStringUtils.equals("oldGroupId", attr.getCode())) {
                        oldGroupId = attr.getValue();
                    }
                    if (KiteStringUtils.equals("oldProvinceCode", attr.getCode())) {
                        oldProvinceCode = attr.getValue();
                        regionCodes.add(oldProvinceCode);
                    }
                    if (KiteStringUtils.equals("oldEparchyCode", attr.getCode())) {
                        oldEparchyCode = attr.getValue();
                        regionCodes.add(oldEparchyCode);
                    }
                    if (KiteStringUtils.equals("oldRegionId", attr.getCode())) {
                        oldRegionId = attr.getValue();
                        regionCodes.add(oldRegionId);
                    }
                    if (KiteStringUtils.equals("groupOldCustName", attr.getCode())) {
                        groupOldCustName = attr.getValue();
                    }
                }
                oldLocationValue = KiteStringUtils.join(regionCodes, SymbolConsts.COMMA);
                List<String> valueList = new ArrayList<String>();
                valueList.add(oldProvinceCode);
                valueList.add(oldEparchyCode);
                valueList.add(oldRegionId);
                oldLocationValueDesc = LocalAttrHelper.getRegionNames(valueList, SymbolConsts.HYPHEN);
            }

            for (CommonAttrVO commonAttr : commonAttrList) {
                if (KiteStringUtils.equals("cust_info_name", commonAttr.getFieldName())) {
                    commonAttr.setValue(groupOldCustName);
                    commonAttr.setValueDesc(groupOldCustName);
                    SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValue(sceneInstId,
                        commonAttr.getFieldName(), groupOldCustName, groupOldCustName);
                }
                if (KiteStringUtils.equals("cust_info_custcode", commonAttr.getFieldName())) {
                    commonAttr.setValue(oldGroupId);
                    commonAttr.setValueDesc(oldGroupId);
                    SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValue(sceneInstId,
                        commonAttr.getFieldName(), oldGroupId, oldGroupId);
                }
                if (KiteStringUtils.equals("contact_info_location", commonAttr.getFieldName())) {
                    commonAttr.setValue(oldLocationValue);
                    commonAttr.setValueDesc(oldLocationValueDesc);
                    SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValue(sceneInstId,
                        commonAttr.getFieldName(), oldLocationValue, oldLocationValueDesc);
                }
            }
        }
        CustInfoVO custInfoVO = new CustInfoVO();
        custInfoVO.setCustInfoAttr(commonAttrList);

        // 收费方产品补录，客户信息模块新增链接，跳转到发起方订单详情
        if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER)) {
            KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
            String offerId = sceneInst.getInstRelGraph().getVertex(sceneInst.getRootInstType(), sceneInst.getRootInstId()).getSpecId();
            List<DcPublic> dcPublicList = DcPublicCache.get("20210719001");
            if (Objects.nonNull(dcPublicList)) {
                // 是否收费方产品
                boolean flag = dcPublicList.stream().anyMatch(dcPublic -> "2".equals(dcPublic.getCodec()) && dcPublic.getCodeb().equals(offerId));
                if(flag) {
                    String orderId = querySceneInstService.getExtParameterValue(sceneInstId, "fallPlaceOrderId");
                    String catagoryId = Optional.ofNullable(OfferCache.get(offerId)).map(Offer::getCateId).orElse(null);
                    String authSessionId = String.valueOf(ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("session_id"));
                    String url = getOrderDetailUrl(orderId, catagoryId, authSessionId);
                    custInfoVO.setOrderDetailBtn("发起方订单信息查询");
                    custInfoVO.setOrderDetailUrl(url);
                }
            }
        }

        SceneNewOfferSeneVO sceneAccountInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        sceneAccountInfoVo.setCustInfo(custInfoVO);

        return Collections.singletonList(custInfoVO);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String serviceOfferId = (String) Optional
            .ofNullable(querySceneInstService.getSceneInst(context.getSceneVo().getSceneInstId()))
            .map(KiteSceneInst::getServiceOfferId).orElse("");
        List<InstAttrDTO> attrConfigs = queryScenePersonService.listCustInfoAttrs(context.getAcceptRequest().getSceneInstId())
            .getResultObject();
        KitePosCustomerDTO custInfo = querySceneInstService.getExtParameterValue(context.getSceneVo().getSceneInstId(), "customer");
        attrConfigs.forEach(t -> {
            if (Objects.isNull(custInfo)) {
                return;
            }
            if (KiteStringUtils.equals("cust_info_name", t.getFieldName()) && KiteStringUtils.isEmpty(t.getValueDesc())) {
                t.setValue(custInfo.getName());
                t.setValueDesc(custInfo.getName());
            }
            if (KiteStringUtils.equals("cust_info_custcode", t.getFieldName()) && KiteStringUtils.isEmpty(t.getValueDesc())) {
                t.setValue(custInfo.getGroupId());
                t.setValueDesc(custInfo.getGroupId());
            }
            if (KiteStringUtils.equals("contact_info_location", t.getFieldName()) && KiteStringUtils.isEmpty(t.getValueDesc())) {
                StringBuilder valueDesc = new StringBuilder();
                valueDesc.append(AreaNameCache.get(custInfo.getEparchyProvince() + "-" + custInfo.getEparchyProvince())).append("-").append(AreaNameCache.get(custInfo.getEparchyProvince() + "-" + custInfo.getEparchyCity())).append("-").append(AreaNameCache.get(custInfo.getEparchyProvince() + "-" + custInfo.getEparchyArea()));
                t.setValue(valueDesc.toString());
                t.setValueDesc(valueDesc.toString());
            }
        });
        CustInfoVO custInfoVO = new CustInfoVO();
        List<CommonAttrVO> commonAttrVO = AssemblyAttrDtoUtils.assemblyCommonVO(attrConfigs);
        commonAttrVO.forEach(commonAttr -> {
            if (KiteStringUtils.equals(commonAttr.getFieldName(), "cust_info_name")
                && KiteStringUtils.equals(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_ORDER_DETAIL)) {
                commonAttr.setAttrValueTypeId("98F");
                commonAttr.setPageUrl("AttrCustInfoDetail");
            }
            else {
                commonAttr.setIsEdit("F");
                commonAttr.setAttrValueTypeId("TT");
            }
        });
        custInfoVO.setCustInfoAttr(commonAttrVO);

        SceneNewOfferSeneVO sceneAccountInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        sceneAccountInfoVo.setCustInfo(custInfoVO);

        return Collections.singletonList(custInfoVO);
    }

    /**
     * 收费方产品补录，获取发起方订单详情页面地址
     * @author zhang.song
     * @date 2022-02-16 16:54
     * @param orderId
     * @param catagoryId
     * @param authSessionId
     * @return java.lang.String
     */
    private static String getOrderDetailUrl(String orderId, String catagoryId, String authSessionId) {
        String url = "/oprateRouter/index.html?menuUrl=/query/orders/todetail?orderId="+orderId+"&orderDetail=true&goodsCategoryId="+catagoryId+"&authSessionId="+authSessionId+"&menuValidFlag=false";
        return url;
    }
}
